<script>
import {Affix} from 'view-design';
import {on} from "view-design/src/utils/dom";

function getScroll(target, top) {
	const prop = top ? 'pageYOffset' : 'pageXOffset';
	const method = top ? 'scrollTop' : 'scrollLeft';

	let ret = target[prop];

	if (typeof ret !== 'number') {
		ret = window.document.documentElement[method];
	}

	return ret;
}

function getOffset(element) {
	const rect = element.getBoundingClientRect();

	const scrollTop = getScroll(document.querySelector('.backend-root-right-content'), true);
	const scrollLeft = getScroll(document.querySelector('.backend-root-right-content'));

	const docEl = window.document.body;
	const clientTop = docEl.clientTop || 0;
	const clientLeft = docEl.clientLeft || 0;

	return {
		top: rect.top + scrollTop - clientTop,
		left: rect.left + scrollLeft - clientLeft
	};
}

export default {
	name: Affix.name,

	registryName: 'LtAffix',

	mixins: [Affix],

	mounted() {
		on(document.querySelector('.backend-root-right-content'), 'scroll', this.handleScroll, this.useCapture);
	},

	methods: {
		handleScroll () {
			const affix = this.affix;
			const scrollTop = getScroll(document.querySelector('.backend-root-right-content'), true);
			const elOffset = getOffset(this.$el);
			const windowHeight = document.querySelector('.backend-root-right-content').innerHeight;
			const elHeight = this.$el.getElementsByTagName('div')[0].offsetHeight;

			// Fixed Top
			if ((elOffset.top - this.offsetTop) < scrollTop && this.offsetType === 'top' && !affix) {
				this.affix = true;
				this.slotStyle = {
					width: this.$refs.point?.clientWidth + 'px',
					height: this.$refs.point?.clientHeight + 'px'
				};
				this.slot = true;
				this.styles = {
					top: `${this.offsetTop}px`,
					left: `${elOffset.left}px`,
					width: `${this.$el.offsetWidth}px`
				};

				this.$emit('on-change', true);
			} else if ((elOffset.top - this.offsetTop) > scrollTop && this.offsetType === 'top' && affix) {
				this.slot = false;
				this.slotStyle = {};
				this.affix = false;
				this.styles = null;

				this.$emit('on-change', false);
			}

			// Fixed Bottom
			if ((elOffset.top + this.offsetBottom + elHeight) > (scrollTop + windowHeight) && this.offsetType === 'bottom' && !affix) {
				this.affix = true;
				this.styles = {
					bottom: `${this.offsetBottom}px`,
					left: `${elOffset.left}px`,
					width: `${this.$el.offsetWidth}px`
				};

				this.$emit('on-change', true);
			} else if ((elOffset.top + this.offsetBottom + elHeight) < (scrollTop + windowHeight) && this.offsetType === 'bottom' && affix) {
				this.affix = false;
				this.styles = null;

				this.$emit('on-change', false);
			}
		}
	}
}
</script>
